/**
 * 
 */
package com.eshopper.user.controller;

import java.util.Date;

import javax.annotation.Resource;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.eshopper.user.model.User;
import com.eshopper.user.security.StringUtils;
import com.eshopper.user.service.UserService;
import com.eshopper.user.util.UserServiceUtil;

/**
 * @author Arun Kumar, Nov 26, 2014
 *
 */
@Controller
public class UserController {
	
	@Resource
	UserService service;

	@RequestMapping(value = { "/login", "/user/form" }, method = RequestMethod.GET)
	public ModelAndView form(
			@RequestParam(value = "error", required = false) String error,
			@RequestParam(value = "logout", required = false) String logout) {

		ModelAndView model = new ModelAndView();

		if (error != null) {
			model.addObject("error", "Invalid username and password!");
		}

		if (logout != null) {
			model.addObject("msg", "You've been logged out successfully.");
		}

		model.setViewName("login-tiles");

		return model;

	}
	
	public static User getCurrentUser()
	{
		Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
	    if (principal instanceof UserDetails) 
	    {
	    	String email = ((UserDetails) principal).getUsername();
	    	User loginUser = UserServiceUtil.findUserByEmail(email);
	    	return loginUser; //new SecurityUser(loginUser);
	    }
	    return null;
	}

	/**
     * <p>User form request.</p>
     * 
     * <p>Expected HTTP GET and request '/user/form'.</p>
     */
	/*@RequestMapping(value="/user/form", method=RequestMethod.GET)
    public ModelAndView form() {
    	
    	return new ModelAndView("login-tiles");
    }*/
    
    /**
     * <p>Saves a user.</p>
     * 
     * <p>Expected HTTP POST and request '/user/form'.</p>
     */
    @RequestMapping(value="/user/form", method=RequestMethod.POST)
    public String form(User user, Model model, RedirectAttributes redirectAttributes ) {
    	
        if (user.getCreateDate() == null) {
        	user.setCreateDate(new Date());
        }
        
        String password = StringUtils.generateRandomPassword();
        
        user.setPasswod(password);
        
        redirectAttributes.addFlashAttribute("password", password);
        
        user = service.addUser(user);
        
        return "redirect:/user/form.html";
    }
}
